package com.android.support.lib.universal.views;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PaintFlagsDrawFilter;
import android.graphics.Path;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.RectF;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;

import com.android.support.lib.universal.utils.UtilProportion;

/**
 * Created by Administrator on 2017/5/22.
 */

public class RoundView extends View {
    public RoundView(Context context) {
        super(context);
        onCreate();
    }

    public RoundView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        onCreate();
    }

    private void onCreate() {
        Paint paint=new Paint();
        paint.setAntiAlias(true);
        paint.setDither(true);
        setLayerType(LAYER_TYPE_HARDWARE, paint);
    }

    Bitmap bitmap;
    private float mRadus = 30 * UtilProportion.getInstance(getContext()).getHorizontalProportion();
    private Path path;
    private Paint paint;

    @Override
    public void draw(Canvas canvas) {
        //Log.e("test", "1:\t width:\t" + getWidth() + "\theight:\t" + getHeight());
        canvas.drawColor(Color.parseColor("#71A7C7"));
        super.draw(canvas);
        if (bitmap != null && !bitmap.isRecycled()) {
            canvas.drawBitmap(bitmap, 0, 0, null);
        }
        if (path == null) {
            path = new Path();
            path.addRoundRect(new RectF(0 - mRadus / 2, 0 - mRadus / 2, getWidth() + mRadus / 2, getHeight() + mRadus / 2), mRadus, mRadus, Path.Direction.CW);
            paint = new Paint();
            paint.setColor(Color.TRANSPARENT);
            paint.setAntiAlias(true);
            paint.setStyle(Paint.Style.STROKE);
            paint.setStrokeWidth(mRadus);
            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
        }
        canvas.setDrawFilter(new PaintFlagsDrawFilter(0, Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG));
        canvas.drawPath(path, paint);
    }

    public void setBitmap(Bitmap bitmap) {
        this.bitmap = bitmap;
        invalidate();
    }

    public void recycle() {
        if (bitmap != null && !bitmap.isRecycled()) {
            bitmap.recycle();
            bitmap = null;
            setBackground(null);
            System.gc();
        }
    }
}
